package com.horizon.manage.endpoint.service.impl;

import com.horizon.common.constrants.HorizonResultCodeEnum;
import com.horizon.manage.endpoint.entity.Endpoint;
import com.horizon.manage.endpoint.mapper.EndpointMapper;
import com.horizon.manage.endpoint.service.IEndpointService;
import com.horizon.modules.system.entity.UserInfo;
import com.horizon.modules.system.service.IUserService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 终端服务.
 *
 * @author zhaoshb
 * @since 2022/12/21 22:00
 */
@Service
@AllArgsConstructor
public class EndpointServiceIml extends BaseServiceImpl<EndpointMapper, Endpoint> implements IEndpointService {

    private static final Logger logger = LoggerFactory.getLogger(EndpointServiceIml.class);

    private static final String ENDPOINT_CACHE_NAME = "endpointCache";

    private IUserService userService;

    @Override
    public HorizonResultCodeEnum endpointAuth(Long endpointId, String userName, String password) {
        Endpoint endpoint = getById(endpointId);
        if (Objects.isNull(endpoint)) {
            logger.info("endpoint [{}] auth failed,cause endpoint not exist.", endpointId);
            return HorizonResultCodeEnum.ENDPOINT_AUTH_FAILED;
        }
        UserInfo userInfo = userService.userInfo(endpoint.getTenantId(), userName, password);
        if (Objects.isNull(userInfo)) {
            logger.info("endpoint [{}] auth failed,cause user not exist or user name [{}] or password [{}] not correct.", endpointId, userName, password);
            return HorizonResultCodeEnum.ENDPOINT_AUTH_FAILED;
        }
        return HorizonResultCodeEnum.SUCCEED;
    }

    @Cacheable(cacheNames = ENDPOINT_CACHE_NAME, key = "#p0")
    public Endpoint queryEndpointById(Long endpointId) {
        return getById(endpointId);
    }

    @Override
    @CachePut(cacheNames = ENDPOINT_CACHE_NAME, key ="#p0.id")
    public boolean save(Endpoint entity) {
        return super.save(entity);
    }

    @Override
    @CacheEvict(cacheNames = ENDPOINT_CACHE_NAME, key = "#p0")
    public boolean deleteById(Long id) {
        return getBaseMapper().deleteById(id) == 1;
    }

    @Override
    @CacheEvict(cacheNames = ENDPOINT_CACHE_NAME, key = "#p0.id")
    public boolean updateById(Endpoint entity) {
        return super.updateById(entity);
    }
}
